#!/usr/bin/python
# -*- encoding: utf-8

import sys, urllib, urllib2
import xbmcplugin, xbmcgui, xbmcaddon

def getParams():
    param = []
    paramstring = sys.argv[2]
    if len(paramstring) >= 2:
        params = sys.argv[2]
        cleanedparams = params.replace('?', '')
        if (params[len(params) - 1] == '/'):
            params = params[0:len(params) - 2]
        pairsofparams = cleanedparams.split('&')
        param = {}
        for i in range(len(pairsofparams)):
            splitparams = {}
            splitparams = pairsofparams[i].split('=')
            if (len(splitparams)) == 2:
                param[splitparams[0]] = splitparams[1]
                            
    return param

def tryGetStrParam(params, name, default = None):
    param = default
    
    try: 
      param = urllib2.unquote(params[name])
    except:
      pass

    return param

def tryGetIntParam(params, name, default = None):
    param = default
    
    try: 
      param = int(params[name])
    except:
      pass

    return param

def showError():
    print "error"
    error = sys.exc_info()[0]
    print error
    dialog = xbmcgui.Dialog()
    dialog.ok("Chyba", "Chyba pri čítaní obsahu. Skúste znova.")
    
def addFolder(name, subUrl, fromPage = None, image = "DefaultFolder.png"):
    encodedParams = ""
        
    if fromPage is None:
        encodedParams = urllib.urlencode({"sub" : subUrl})
    else:
        encodedParams = urllib.urlencode({"sub" : subUrl, "page" : fromPage})
                
    folderUrl = sys.argv[0] + "?" + encodedParams
    
    item = xbmcgui.ListItem(name, iconImage = image, thumbnailImage = image)
    item.setInfo(type="Video", infoLabels = { "Title": name })
    xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url = folderUrl, listitem = item, isFolder = True)

def addLink(name, videoId, image, plot, fromFolder = None):
    encodedParams = urllib.urlencode({'id' : videoId})
    linkUrl = sys.argv[0] + "?" + encodedParams

    item = xbmcgui.ListItem(name, fromFolder, iconImage = image, thumbnailImage = image)
    item.setInfo(type = "Video", infoLabels = { "Title" : name, "tvshowtitle" : fromFolder, "plot" : plot })
    item.setProperty('IsPlayable', 'true')
    xbmcplugin.addDirectoryItem(handle = int(sys.argv[1]), url = linkUrl, listitem = item)
